package user;

import net.rim.device.api.command.Command;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.TextSpinBoxField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.SpinBoxFieldManager;
import net.rim.device.api.util.StringProvider;

public class GeneratorSelectionScreen extends MainScreen {

	private static final int SECONDS_IN_MINUTE = 60;
	private static final long MILLISECONDS_IN_SECOND = 1000;
	private static final int POSITION_IN_LIST = 0; // First menu item
	private static final int PRIORITY = 0; // TODO Find out what this does
	
	private TextSpinBoxField spinBoxTime = null;
	private String[] timeValues = new String[]{
		"1 minute",
		"2 minutes",
		"5 minutes",
		"10 minutes",
		"30 minutes"
	};
	
	// No generics in BB! J2ME O_o
	private CheckboxField[] sources = getSourceCheckBoxes();
	
	public GeneratorSelectionScreen(){
		LabelField title = new LabelField("Select Entropy Sources:", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
		setTitle(title);
		
		// Add generator checkboxes to screen
		for(int i = 0; i < sources.length; i++){
			add(sources[i]);
		}
		
		// Setup time selection
		SpinBoxFieldManager spinBoxManager = new SpinBoxFieldManager();
		spinBoxManager.setVisibleRows(3);
		spinBoxTime = new TextSpinBoxField(timeValues);
		spinBoxManager.add(spinBoxTime);
		add(spinBoxManager);
	}
	
	private CheckboxField[] getSourceCheckBoxes() {
		String[] sourceNames = GeneratorUser.getSourceNames();
		CheckboxField[] sources = new CheckboxField[sourceNames.length];
		for(int i = 0; i < sourceNames.length; i++){
			sources[i] = new CheckboxField(sourceNames[i], true);
		}
		return sources;
	}

	protected void makeMenu(Menu menu, int instance) {
		long stopTime = getStopTime();
		MenuItem startGenerator = new MenuItem(new StringProvider("Start Generator"), POSITION_IN_LIST, PRIORITY);
		startGenerator.setCommand(new Command(new GeneratorUser(sources, stopTime)));
		menu.add(startGenerator);
	}

	private long getStopTime() {
		long currentTime = System.currentTimeMillis();
		String strMinutes = timeValues[spinBoxTime.getSelectedIndex()].toString();
		int minutes = Integer.parseInt(strMinutes.substring(0, strMinutes.indexOf(" ")));
		long seconds = minutes * SECONDS_IN_MINUTE;
		long milliseconds = seconds * MILLISECONDS_IN_SECOND;
		return currentTime + milliseconds;
	}

}
